package csc.fresher.commons;

import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.component.FacesComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import net.tanesha.recaptcha.ReCaptcha;
import net.tanesha.recaptcha.ReCaptchaFactory;

@FacesComponent("csc.fresher.commons.recaptcha")
public class RecaptchaComponent extends UIInput {
	 static final String RecaptchaComponent_FAMILY = "RecaptchaComponentFamily";
		private String publicKey;
		private String privateKey;


		@Override
		public final String getFamily() {
			return RecaptchaComponent_FAMILY;
		}

		public String getPublicKey() {
			return publicKey;
		}

		public void setPublicKey(String publicKey) {
			this.publicKey = publicKey;
		}

		public String getPrivateKey() {
			return privateKey;
		}

		public void setPrivateKey(String privateKey) {
			this.privateKey = privateKey;
		}

		@Override
		public void decode(FacesContext arg0) {
			super.decode(arg0);
		}

		@Override
		public void encodeBegin(FacesContext arg0) throws IOException {
			// TODO Auto-generated method stub
			super.encodeBegin(arg0);
		}

		@Override
		public void encodeEnd(FacesContext arg0) throws IOException {
			
			String publicKey = this.getPublicKey();
			String privateKey = this.getPrivateKey();
		
			if (publicKey == null || privateKey == null) {
				throw new IllegalArgumentException("reCaptcha keys cannot be null. This is probably a component bug.");
			}

			ReCaptcha c = ReCaptchaFactory.newReCaptcha(publicKey, privateKey, false);
			String createRecaptchaHtml = c.createRecaptchaHtml(null, null);
			ResponseWriter writer = arg0.getResponseWriter();
			writer.write(createRecaptchaHtml);
		}

		/*
		 * This is overridden to make sure that the Captcha validator which is included in
		 * this custom component gets executed
		 * (non-Javadoc)
		 * @see javax.faces.component.UIInput#validate(javax.faces.context.FacesContext)
		 */
		@Override
		public void validate(FacesContext ctx) {
			Validator[] validators = getValidators();
			for (Validator v : validators) {
				try {
					v.validate(ctx, this, null);
				} catch (ValidatorException ex) {
					setValid(false);
					FacesMessage message = ex.getFacesMessage();
					if (message != null) {
						message.setSeverity(FacesMessage.SEVERITY_ERROR);
						ctx.addMessage(getClientId(ctx), message);
					}
				}
			}
			super.validate(ctx);
		}
}
